package Servlet;

import Bean.Brand;
import Bean.CarDetail;
import Dao.BrandDao;
import Dao.CarDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

@WebServlet("/car/*")
public class CarServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理乱码问题
        req.setCharacterEncoding("utf-8");
        //获取/*具体的路径
        String path = req.getPathInfo();
        System.out.println(path);
        //根据path判断逻辑代码(默认路径为/car或/car/就显示所有车辆信息)
        if (path == null || path.equals("/")) {
            //调用DAO查询方法，得到装有所有车辆信息的集合
            ArrayList<CarDetail> list = CarDao.getAllCar();
            //将集合放到request请求域对象中
            req.setAttribute("list", list);
            //将请求转发给一个负责显示的jsp
            req.getRequestDispatcher("/WEB-INF/carList.jsp").forward(req, resp);
        } else if (path.equals("/add")) {
            //先从数据库查询所有品牌信息
            ArrayList<Brand> list = BrandDao.getAllBrand();
            //将品牌信息封装好后发给from.jsp
            req.setAttribute("list", list);
            req.getRequestDispatcher("/WEB-INF/form.jsp").forward(req, resp);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理乱码问题
        req.setCharacterEncoding("utf-8");
        //获取/*具体的路径
        String path = req.getPathInfo();
        //根据path判断逻辑代码
        if(path.endsWith("/save")) {
            //获取表单数据
            String cname = req.getParameter("cname");
            int brandid = Integer.parseInt(req.getParameter("brandid"));
            String content = req.getParameter("content");
            int price = Integer.parseInt(req.getParameter("price"));
            String date = req.getParameter("date");

            //得到的时间是字符串，要解析成date类型
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date newDate;
            try {
                newDate = sdf.parse(date);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            //将表单获取的数据封装成对象传给Dao
            CarDetail car = new CarDetail(0, cname, content, newDate, price, brandid);
            int i = CarDao.addCar(car);
            if(i>0){
                //重定向(添加成功，刷新页面)
                resp.sendRedirect("/car");
            }else{
                //将添加失败信息传给msg显示
                req.setAttribute("smg","添加失败");
                req.getRequestDispatcher("/WEB-INF/msg.jsp").forward(req,resp);
            }
        }
    }
}
